package org.jkd.ams.client;

import java.net.InetSocketAddress;
import java.util.Date;

import org.apache.mina.core.future.ConnectFuture;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.ProtocolCodecFilter;
import org.apache.mina.filter.logging.LoggingFilter;
import org.apache.mina.transport.socket.nio.NioSocketConnector;
import org.jkd.ams.core.codec.MDRProtocolClientCodecFactory;
import org.jkd.ams.core.messages.MDRRequest;


public class AmsClient {
	
	private static final long CONNECT_TIMEOUT = 30*1000L;

	public static void main(String[] args) {
		
		final RequestParameters parameters = readRequestParameters();
		
		final MDRRequest request = generateRequest(parameters);
		
		final NioSocketConnector connector = buildConnector();
		
		connector.setHandler(new ClientSessionHandler(request));
		
		IoSession session;
		
		for (;;) {
			
			final ConnectFuture connectFuture = connector.connect(new InetSocketAddress(parameters.hostName, parameters.port));
			connectFuture.awaitUninterruptibly();
			session = connectFuture.getSession();
			break;
		}
		
		session.getCloseFuture().awaitUninterruptibly();
		connector.dispose();
	}

	private static RequestParameters readRequestParameters() {
		
		final RequestParameters parameters = new RequestParameters();
		parameters.hostName = "localhost";
		parameters.port = 20001;
		parameters.employeeId = 1001;
		parameters.move = 0;
		
		return parameters;
	}
	
	private static MDRRequest generateRequest(RequestParameters parameters) {
		
		final MDRRequest request = new MDRRequest();
		request.setMessageId(1);
		request.setEmployeeId(parameters.employeeId);
		request.setMove(parameters.move);
		request.setTimeStamp(new Date().getTime());
		
		return request;
	}

	private static NioSocketConnector buildConnector() {
		
		final NioSocketConnector connector = new NioSocketConnector();
		connector.setConnectTimeoutMillis(CONNECT_TIMEOUT);
		connector.getFilterChain().addLast("codec", new ProtocolCodecFilter(new MDRProtocolClientCodecFactory()));
		connector.getFilterChain().addLast("logger", new LoggingFilter());
		
		return connector;
	}

	
	
	private static class RequestParameters{
		
		String hostName;

		int port;
		
		public byte move;

		public int employeeId;

		
	}
}
